//
//  SHEViewController.m
//  SHEPuzzleFigure
//
//  Created by SW mini on 2019/11/25.
//  Copyright © 2019 Figure. All rights reserved.
//

#import "SHEViewController.h"

@interface SHEViewController ()

@property (weak, nonatomic) IBOutlet UILabel *dateTabel;
@property (weak, nonatomic) IBOutlet UILabel *numberLabel;
@property (weak, nonatomic) IBOutlet UIButton *thumbnailImgV;
@property (weak, nonatomic) IBOutlet UIView *puzzleView;
@property (weak, nonatomic) IBOutlet UIButton *autoButton;

@property (strong,nonatomic)dispatch_source_t sourceTimer;
@property (assign,nonatomic)NSInteger gcdIdx;
@property (assign,nonatomic)NSInteger numIdx;

#pragma mark - 选项
/// 图片
@property (nonatomic, strong) UIImage *image;
/// 矩阵阶数
@property (nonatomic, assign) NSInteger matrixOrder;


#pragma mark - 状态
/// 标记正在自动拼图
@property (atomic, assign) BOOL isAutoGaming;
/// 当前游戏状态
@property (nonatomic, strong) PuzzleStatus *currentStatus;
/// 完成时的游戏状态
@property (nonatomic, strong) PuzzleStatus *completedStatus;
/// 保存的游戏状态
@property (nonatomic, strong) PuzzleStatus *savedStatus;


@end

@implementation SHEViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [super setTitleView:self.detailsDcit[@"title"]];
    [super createBackBtn];
    

//    self.gcdIdx = 0;
//    self.numIdx = 0;

    SHELoadingView *loadingView = [SHELoadingView initWithXib:CGRectMake(0, 0, SCREEN_WIDTH_S, SCREEN_MAX_LENGTH_S)];
    [[UIApplication sharedApplication].keyWindow addSubview:loadingView];
    [loadingView start];
    

    NSString *thumbnailUrl = [NSString stringWithFormat:@"%@%@",API_HOST,_detailsDcit[@"image_url"]];
    [self.thumbnailImgV yy_setImageWithURL:[NSURL URLWithString:thumbnailUrl] forState:UIControlStateNormal placeholder:nil];
    

    self.matrixOrder = self.difficultyInt;//难度
    
    self.puzzleView.frame = CGRectMake(10, 160, SHEWidth-20, SHEWidth-20);
    
    [self updateImageUi];
    
    [self createDispatch_source_t];
}

//缩略图
- (IBAction)thumAction:(id)sender {
    NSString *thumbnailUrl = [NSString stringWithFormat:@"%@%@",API_HOST,_detailsDcit[@"image_url"]];
    YBIBImageData *data1 = [YBIBImageData new];
    data1.imageURL = [NSURL URLWithString:thumbnailUrl];
    data1.projectiveView = _thumbnailImgV;

    YBImageBrowser *browser = [YBImageBrowser new];
    browser.dataSourceArray = @[data1];
    [browser show];
}


- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    dispatch_source_cancel(self.sourceTimer);
}

/**
 * 压缩图片到指定尺寸大小
 *
 * @param image 原始图片
 * @param size 目标大小
 *
 * @return 生成图片
 */
-(UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{
    UIImage * resultImage = image;
    UIGraphicsBeginImageContext(size);
    [resultImage drawInRect:CGRectMake(00, 0, size.width, size.height)];
    UIGraphicsEndImageContext();
    return image;
}

- (void)updateImageUi{
    //初始化图片
    self.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",self.detailsDcit[@"pic_name"]]];//self.puzzleImgV.image;
    //消失一格
    [self onPieceTouch:self.currentStatus.pieceArray.lastObject];
    //打乱
    [self onShuffleMethods];
    
    
}

//保存进度,读取进度,重新开始
- (IBAction)clickBtn:(UIButton *)sender {
    switch (sender.tag) {
        case 1000:{//保存进度
            [self onSaveProgress];
        }
            break;
        case 1001:{//读取进度
            [self onLoadProgress];
        }
            break;
        case 1002:{//重新开始
            [self onResetTheGame];
            [self updateImageUi];
        }
            break;
        case 1003:{//自动
            [self onDoneAutomatically];
        }
            break;
    }
}

/// 自动完成
- (void)onDoneAutomatically{
    if (self.currentStatus.emptyIndex < 0) {
        return;
    }
    
    JXPathSearcher *searcher = nil;
    searcher = [[JXAStarSearcher alloc] init];
    searcher.startStatus = [self.currentStatus copyStatus];
    searcher.targetStatus = [self.completedStatus copyStatus];
    [searcher setEqualComparator:^BOOL(PuzzleStatus *status1, PuzzleStatus *status2) {
        return [status1 equalWithStatus:status2];
    }];
    // 开始搜索
//    NSDate *startDate = [NSDate date];
    NSMutableArray<PuzzleStatus *> *path = [searcher search];
    __block NSInteger pathCount = path.count;
//    NSLog(@"耗时：%.3f秒", [[NSDate date] timeIntervalSince1970] - [startDate timeIntervalSince1970]);
//    NSLog(@"需要移动：%@步", @(pathCount));

    self.numberLabel.text = [NSString stringWithFormat:@"步数：%ld",pathCount];
    
    if (!path || pathCount == 0) {
        return;
    }
    
    // 开始自动拼图
    self.isAutoGaming = YES;
    self.autoButton.enabled = NO;
    
    // 定时信号，控制拼图速度
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.3 repeats:YES block:^(NSTimer * _Nonnull timer) {
        dispatch_semaphore_signal(sema);
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [path enumerateObjectsUsingBlock:^(PuzzleStatus * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            // 等待信号
            dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
            // 刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                // 显示排列
                [self reloadWithStatus:obj];
                // 显示步数
                if (pathCount > 1) {
                    [self.autoButton setTitle:[NSString stringWithFormat:@"自动(%@)", @(pathCount --)] forState:UIControlStateNormal];
                }
                else {
                    [self.autoButton setTitle:@"自动" forState:UIControlStateNormal];
                    self.autoButton.enabled = YES;
                    
                    [self alertTitle:@"恭喜" message:@"拼图完成！"];
                    //保存到本地，历史记录列表展示
                    [self oSave];
                }
            });
        }];
        
        // 拼图完成
        [timer invalidate];
        self.currentStatus = [path lastObject];
        self.isAutoGaming = NO;
    });
}

/// 打乱顺序
- (void)onShuffleMethods {
    
    if (self.currentStatus.emptyIndex < 0) {
        return;
    }
//    NSLog(@"打乱顺序：当前为%@阶方阵, 随机移动%@步", @(self.matrixOrder), @(self.matrixOrder * self.matrixOrder * 2));
    [self.currentStatus shuffleCount:self.matrixOrder * self.matrixOrder * 2];
    [self reloadWithStatus:self.currentStatus];
}

/// 重置游戏
- (void)onResetTheGame {
    //重新开始计时器
    [self createDispatch_source_t];
    
    if (!self.image) {
        return;
    }

    if (self.currentStatus) {
        [self.currentStatus removeAllPieces];
    }
    self.currentStatus = [PuzzleStatus statusWithMatrixOrder:self.matrixOrder image:self.image];
    [self.currentStatus.pieceArray enumerateObjectsUsingBlock:^(PuzzlePiece * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj addTarget:self action:@selector(onPieceTouch:) forControlEvents:UIControlEventTouchUpInside];
    }];

    self.completedStatus = nil;
    [self showCurrentStatusOnView:self.puzzleView];
}

/// 保存进度
- (void)onSaveProgress {
    
    if (!self.currentStatus) {
        return;
    }
    
    self.savedStatus = [self.currentStatus  copyStatus];
    [self alertTitle:nil message:@"保存成功,仅在本局内有效"];
}

/// 读取进度
- (void)onLoadProgress  {
    
    if (!self.savedStatus) {
        return;
    }
    
    if (self.currentStatus) {
        [self.currentStatus removeAllPieces];
    }
    self.currentStatus = self.savedStatus;
    
    [self showCurrentStatusOnView:self.puzzleView];
    [self alertTitle:nil message:@"读取成功"];
}

/// 点击方块
- (void)onPieceTouch:(PuzzlePiece *)piece {
    
    PuzzleStatus *status = self.currentStatus;
    NSInteger pieceIndex = [status.pieceArray indexOfObject:piece];
    
    // 挖空一格
    if (status.emptyIndex < 0) {
        // 所选方块成为空格
        [UIView animateWithDuration:0.25 animations:^{
            piece.alpha = 0;
        }];
        status.emptyIndex = pieceIndex;
        // 设置目标状态
        self.completedStatus = [self.currentStatus  copyStatus];
        return;
    }
    
    if (![status canMoveToIndex:pieceIndex]) {
//        NSLog(@"无法移动，target index:%@",  @(pieceIndex));
        return;
    }
    
    [status moveToIndex:pieceIndex];
    [self reloadWithStatus:self.currentStatus];
    
    // 完成一次移动
    self.numberLabel.text = [NSString stringWithFormat:@"步数：%ld",++self.numIdx];
    if ([status equalWithStatus:self.completedStatus]) {
        [self alertTitle:@"恭喜" message:@"拼图完成！"];
        
        //保存到本地，历史记录列表展示
        [self oSave];
    }
}

- (void)oSave{
    //关闭计时器
    dispatch_source_cancel(self.sourceTimer);
    
    //保存到本地，历史记录列表展示
    NSMutableArray *muArr = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"HISTORYLIST"]];
    NSString *time = [_dateTabel.text stringByReplacingOccurrencesOfString:@"s" withString:@""];
    NSDictionary *dic = @{
        @"image_url":_detailsDcit[@"image_url"],
        @"step_num":[_numberLabel.text stringByReplacingOccurrencesOfString:@"步数：" withString:@""],
        @"time":[time stringByReplacingOccurrencesOfString:@"时间：" withString:@""],
        @"title":_detailsDcit[@"title"],
        @"type":_titleStr
    };
    [muArr addObject:dic];
    [[NSUserDefaults standardUserDefaults] setObject:muArr forKey:@"HISTORYLIST"];
}

- (void)showCurrentStatusOnView:(UIView *)view {
    CGFloat size = CGRectGetWidth(view.bounds) / self.matrixOrder;
    NSInteger index = 0;
    for (NSInteger row = 0; row < self.matrixOrder; ++ row) {
        for (NSInteger col = 0; col < self.matrixOrder; ++ col) {
            PuzzlePiece *piece = self.currentStatus.pieceArray[index ++];
            piece.frame = CGRectMake(col * size, row * size, size, size);
            [view addSubview:piece];
        }
    }
}

- (void)reloadWithStatus:(PuzzleStatus *)status {
    [UIView animateWithDuration:0.25 animations:^{
        CGSize size = status.pieceArray.firstObject.frame.size;
        NSInteger index = 0;
        for (NSInteger row = 0; row < self.matrixOrder; ++ row) {
            for (NSInteger col = 0; col < self.matrixOrder; ++ col) {
                PuzzlePiece *piece = status.pieceArray[index ++];
                piece.frame = CGRectMake(col * size.width, row * size.height, size.width, size.height);
            }
        }
    }];
}

//难度
- (void)setMatrixOrder:(NSInteger)matrixOrder {
    if (matrixOrder < 3 || matrixOrder > 5) {
        return;
    }
    _matrixOrder = matrixOrder;
    NSString *title;
    if (matrixOrder == 3) {
        title = @"难度：低";
    }
    else if (matrixOrder == 4) {
        title = @"难度：中";
    }
    else if (matrixOrder == 5) {
        title = @"难度：高";
    }
    [self onResetTheGame];
}

- (void)setImage:(UIImage *)image {
    _image = image;
    [self onResetTheGame];
}

/// 用户提示
- (void)alertTitle:(NSString *)title message:(NSString *)message {
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
//    NSLog(@"内存警告");
}

//计时器
-(void)createDispatch_source_t{
    self.gcdIdx = 0;
    self.numIdx = 0;
    self.numberLabel.text = @"步数：0";
    
    
    //创建全局队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //使用全局队列创建计时器
    _sourceTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //定时器延迟时间
    NSTimeInterval delayTime = 1.0f;
    //定时器间隔时间
    NSTimeInterval timeInterval = 1.0f;
    //设置开始时间
    dispatch_time_t startDelayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC));
    //设置计时器
    dispatch_source_set_timer(_sourceTimer,startDelayTime,timeInterval*NSEC_PER_SEC,0.1*NSEC_PER_SEC);
    //执行事件
    dispatch_source_set_event_handler(_sourceTimer,^{
        dispatch_async(dispatch_get_main_queue(), ^{
            self.dateTabel.text = [NSString stringWithFormat:@"时间：%lds",self.gcdIdx++];
        });
        
    });
    //启动计时器
    dispatch_resume(self.sourceTimer);
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
